import React, { useState, useRef } from 'react';
import ReactDOM from 'react-dom';
import { Card, Switch, Image, Modal, message, Popconfirm } from 'antd';
import AutoTable from '@/components/AutoTable';
import InitForm from '@/components/InitForm';
import { deleteaccount_book, store } from '@/services/dossier';
import { connect } from 'umi';
import { PlusOutlined } from '@ant-design/icons';
import { company } from '@/services/business';
import CompanyName from '@/components/CompanyName';

// type 类型有 table treeselect upload inputnumber datepicker daterange radio select textarea autoinput editor password input

function Accountbook(props) {
  let defaultFields = {
    company_id: {
      value: null,
      type: 'select',
      title: '代账公司',
      name: ['company_id'],
      required: true,
      options: {
        database: company,
        params: {
          is_all: 1,
          type: -1,
          account_user_id: props.user.currentUser.id,
          status: 'completed',
          service_type: 'account',
        },
      },
      col: { span: 24 },
    },
    year: {
      value: null,
      type: 'datepicker',
      title: '年份',
      name: ['year'],
      picker: 'year',
      required: true,
      col: { span: 24 },
    },
    detail: {
      value: null,
      type: 'upload',
      title: '明细账',
      name: ['detail'],
      col: { span: 24 },
      required: false,
      listType: 'file',
      multiple: true,
      limit: 5,
    },
    general_classify: {
      value: null,
      type: 'upload',
      title: '总分类账',
      name: ['general_classify'],
      col: { span: 24 },
      required: false,
      listType: 'file',
      multiple: true,
      limit: 5,
    },
    year_income_tax: {
      value: null,
      type: 'upload',
      title: '年度所得税',
      name: ['year_income_tax'],
      col: { span: 24 },
      required: false,
      listType: 'file',
      multiple: true,
      limit: 5,
    },
  };

  const [vs, cvs] = useState(false), //表单显/隐
    [fields, cf] = useState(defaultFields),
    [iftype, ciftype] = useState({});

  let actionRef = useRef(),
    ChildRef = null;
  function reload() {
    actionRef?.current?.reload();
    ChildRef?.onRefresh();
  }
  const columns = [
    {
      title: '公司名称',
      width: 260,
      dataIndex: 'company_name',
      key: 'company_name',
      render: (_, row) => (
        <CompanyName
          row={{ ...row, name: row?.company_name ?? row.name, id: row?.company_id ?? row.id }}
          reload={reload}
        />
      ),
    },
    {
      title: '年份',
      dataIndex: 'year',
      key: 'year',
      search: false,
    },
    {
      title: '明细账',
      dataIndex: 'detail',
      key: 'detail',
      search: false,
      render: (_, row) => {
        if (!row.detail) {
          return (
            <Image
              width={32}
              height={32}
              style={{ padding: 2 }}
              src={require('@/assets/default.png')}
            ></Image>
          );
        } else {
          return row.detail.map((it, i) => {
            return (
              <a href={it.origin_url} style={{ padding: 2 }} key={i} target={'_blank'}>
                附件{i + 1}
              </a>
            );
          });
        }
      },
    },
    {
      title: '总分类账',
      dataIndex: 'general_classify',
      key: 'general_classify',
      search: false,
      render: (_, row) => {
        if (!row.general_classify) {
          return (
            <Image
              width={32}
              height={32}
              style={{ padding: 2 }}
              src={require('@/assets/default.png')}
            ></Image>
          );
        } else {
          return row.general_classify.map((it, i) => {
            return (
              <a href={it.origin_url} style={{ padding: 2 }} key={i} target={'_blank'}>
                附件{i + 1}
              </a>
            );
          });
        }
      },
    },
    {
      title: '年度所得税申报表',
      dataIndex: 'year_income_tax',
      key: 'year_income_tax',
      search: false,
      render: (_, row) => {
        if (!row.year_income_tax) {
          return (
            <Image
              width={32}
              height={32}
              style={{ padding: 2 }}
              src={require('@/assets/default.png')}
            ></Image>
          );
        } else {
          return row.year_income_tax.map((it, i) => {
            return (
              <a href={it.origin_url} style={{ padding: 2 }} key={i} target={'_blank'}>
                附件{i + 1}
              </a>
            );
          });
        }
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 100,
      render: (text, record, _, action) => [
        <a
          style={{ color: '#1890ff' }}
          onClick={() => {
            cvs(true);
            cf((fields) => {
              for (let i in fields) {
                fields[i].value = record[i];
              }
              return { ...fields };
            });
            ciftype({
              val: 'edit',
              title: '编辑账簿',
              id: record.id,
            });
          }}
        >
          编辑
        </a>,
        <Popconfirm
          placement="bottom"
          title={'确认删除该账簿？'}
          onConfirm={() => {
            deleteaccount_book(record.id).then((res) => {
              if (res.code == 0) {
                message.success('操作成功');
                reload();
              }
            });
          }}
          okText="删除"
          cancelText="取消"
        >
          <a style={{ color: '#f50' }}>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  let extrarender = [
    <div
      className="action"
      title="新增"
      onClick={() => {
        cvs(true);
        cf((fields) => {
          for (let i in fields) {
            fields[i].value = null;
          }
          return { ...fields };
        });
        ciftype({
          val: 'add',
          title: '新增账簿',
        });
      }}
    >
      <PlusOutlined />
    </div>,
  ];

  let saveData = (values) => {
    let { dispatch } = props;
    if (iftype.val == 'add') {
      dispatch({
        type: 'dossier/addaccount_book',
        payload: values,
      }).then((res) => {
        if (res.code == 0) {
          message.success('操作成功');
          reload();
          cvs(false);
        }
      });
    } else if (iftype.val == 'edit') {
      dispatch({
        type: 'dossier/editaccount_book',
        payload: { ...values, id: iftype.id },
      }).then((res) => {
        if (res.code == 0) {
          message.success('操作成功');
          reload();
          cvs(false);
        }
      });
    }
  };

  return (
    <div className="pgcontainer">
      <AutoTable
        pagetitle={props.route.name} //页面标题
        pageextra={extrarender} //页面操作 新增or批量删除
        columns={columns}
        actionRef={actionRef}
        onRef={(node) => (ChildRef = node)}
        path="/wbn-api/account_book"
        //withCard={false}
        //cardtitle = "name" //卡片标题
        //cardavatar = "img_url" //卡片头像
      ></AutoTable>
      <Modal
        maskClosable={false}
        title={iftype.title}
        open={vs}
        onCancel={() => cvs(false)}
        footer={false}
        destroyOnClose={true}
      >
        <InitForm
          fields={fields}
          submitData={(values) => {
            saveData(values);
          }}
          onChange={(changedValues, allValues) => {
            //联动操作
          }}
          submitting={
            props.loading.effects['dossier/addaccount_book'] ||
            props.loading.effects['dossier/editaccount_book'] ||
            !vs
          }
        ></InitForm>
      </Modal>
    </div>
  );
}

export default connect(({ dossier, loading, user }) => ({
  dossier,
  loading,
  user,
}))(Accountbook);
